<template>
  <div class="homepage">
    <!-- Use the new indexFrame component for the header -->
    
    <!-- Hero Section Placeholder -->
    <section class="hero-section">
      <!-- 视频背景 - 使用正确的相对路径 -->
      <video autoplay muted loop playsinline class="hero-video" controlslist="nodownload nofullscreen noremoteplayback"
        disablepictureinpicture oncontextmenu="return false">
        <source src="@/assets/weather/index.mp4" type="video/mp4">
      </video>
      <div class="hero-content">
        <h2>AMAZING<br />MOUNTAIN TO<br />EXPLORE</h2>
        <!-- More content can be added here -->
      </div>
    </section>
    <main>
      <section class="scenicmain scenic-content-maponly">
        <china-map :scenicList="scenicList" />
      </section>

      <section class="hot-scenic-spots no-bg">
        <h2 class="hot-title">热门景点</h2>
        <Swiper
          :slides-per-view="2"
          :space-between="30"
          :centered-slides="true"
          effect="coverflow"
          :coverflow-effect="{ rotate: 0, stretch: 0, depth: 100, modifier: 1, slideShadows: false }"
          :loop="true"
          :autoplay="{ delay: 3000, disableOnInteraction: false }"
          navigation
          class="hot-scenic-swiper-coverflow"
        >
          <SwiperSlide v-for="spot in top4HotScenicSpots" :key="spot.id">
            <div class="hot-scenic-card-large" @click="goToScenicDetail(spot.id)">
              <img class="hot-scenic-img-large" :src="spot.img" alt="热门景点图片" />
              <div class="hot-scenic-info-large">
                <div class="hot-scenic-title-large">{{ spot.title }}</div>
                <div class="hot-scenic-desc-large">{{ spot.desc }}</div>
                <div class="hot-scenic-actions-large">
                  <button class="like-button"><span class="like-icon">★</span> 已点赞 ({{ spot.likes }})</button>
                </div>
              </div>
            </div>
          </SwiperSlide>
        </Swiper>
      </section>

      <!-- 热门攻略 -->
      <section class="hot-scenic-spots no-bg">
        <h2 class="hot-title">热门攻略</h2>
        <Swiper
          :slides-per-view="2"
          :space-between="30"
          :centered-slides="true"
          effect="coverflow"
          :coverflow-effect="{ rotate: 0, stretch: 0, depth: 100, modifier: 1, slideShadows: false }"
          :loop="true"
          :autoplay="{ delay: 3000, disableOnInteraction: false }"
          navigation
          class="hot-scenic-swiper-coverflow"
        >
          <SwiperSlide v-for="strategy in hotStrategies" :key="strategy.id">
            <div class="hot-strategy-card-row" @click="goToStrategyDetail(strategy.id)">
              <img class="hot-strategy-img-side" :src="strategy.img || defaultAvatar" alt="热门攻略图片" />
              <div class="hot-strategy-info-side">
                <div class="hot-strategy-title">{{ strategy.title }}</div>
                <div class="hot-strategy-desc">{{ stripHtmlTags(strategy.desc).slice(0, 100) }}...</div>
                <div class="hot-strategy-bottom-side">
                  <div class="hot-strategy-author">
                    <img :src="strategy.userAvatar || defaultAvatar" alt="头像" class="hot-strategy-author-avatar" />
                    <span class="hot-strategy-author-name">{{ strategy.username }}</span>
                  </div>
                  <button class="hot-strategy-like-btn"><span class="like-icon">★</span> 已点赞 ({{ strategy.likes }})</button>
                </div>
              </div>
            </div>
          </SwiperSlide>
        </Swiper>
      </section>
    </main>
  </div>
</template>

<script>
import IndexFrame from '../indexFrame.vue';
import WeatherForecast from '../../components/WeatherForecast.vue';
import axios from 'axios';
import ChinaMap from '@/components/ChinaMap.vue';
import { regionMap } from '@/utils/regionMap'
import { Swiper, SwiperSlide } from 'swiper/vue';
import SwiperCore, { Autoplay, EffectCoverflow, Navigation } from 'swiper';
import 'swiper/css';
import 'swiper/css/effect-coverflow';
import 'swiper/css/navigation';
SwiperCore.use([Autoplay, EffectCoverflow, Navigation]);

export default {
  name: 'HomePage',
  components: {
    IndexFrame,
    WeatherForecast,
    ChinaMap,
    Swiper,
    SwiperSlide
  },
  data() {
    return {
      scenicList: [],
      scenicMinis: [],
      hotScenicSpots: [],
      hotStrategies: [],
      defaultAvatar: 'https://via.placeholder.com/30',
      hotScenicScrollTimer: null,
      hotStrategyScrollTimer: null
    };
  },
  computed: {
    top4HotScenicSpots() {
      // 按点赞数降序取前4
      return [...this.hotScenicSpots].sort((a, b) => (b.likes || 0) - (a.likes || 0)).slice(0, 4);
    }
  },
  mounted() {
    const loginId = localStorage.getItem('loginId');
    // 只有登录后才统计访问
    if (loginId && loginId !== 'guest') {
      axios.post('http://localhost:8080/api/visit', null, { params: { loginId } });
    }
    this.fetchScenicList();
    this.fetchHotScenicSpots();
    this.fetchHotStrategies();
    this.$nextTick(() => {
      // 视频禁用右键
      const video = document.querySelector('.hero-video');
      if (video) {
        video.addEventListener('contextmenu', (e) => e.preventDefault());
        video.addEventListener('dragstart', (e) => e.preventDefault());
      }
    });
  },
  beforeUnmount() {
    clearInterval(this.hotScenicScrollTimer);
    clearInterval(this.hotStrategyScrollTimer);
  },
  methods: {
async fetchScenicList() {
  console.log("🔥 fetchScenicList 被调用");
  console.log('regionMap:', regionMap);
console.log('regionMap keys:', Object.keys(regionMap));
console.log('regionMap[180]:', regionMap[180]);
  try {
    const res = await axios.get('http://localhost:8080/mw/ScenicSpotList');
    let list = Array.isArray(res.data) ? res.data : [res.data];
    console.log("step1, 景区数量:", list.length, "list:", list, "Array.isArray:", Array.isArray(list));
    console.log("list keys", Object.keys(list));
    console.log("list prototype", Object.getPrototypeOf(list));

    // 封装带超时的请求
    function fetchWithTimeout(promise, ms = 4000) {
      return Promise.race([
        promise,
        new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms))
      ]);
    }

    console.log("before Promise.all");

    // 并发调用 /api/amap/geocode 给每个景区补经纬度
    const scenicListWithCoords = await Promise.all(
      list.map(async (spot, idx) => {
        // 在 map 回调内部打印 regionId
        console.log(`[${idx}] regionId:`, spot.regionId, typeof spot.regionId);

        const region = regionMap[Number(spot.regionId)];
        console.log(`[${idx}] regionId:`, spot.regionId, typeof spot.regionId, "region:", region);

        if (!region) {
          console.warn(`[${idx}] 区域未匹配，跳过`, spot.scenicAreaName);
          return spot;
        }

        try {
          const geoRes = await axios.get('/api/amap/geocode', {
            params: {
              province: region.province,
              city: region.city,
              scenicName: spot.scenicAreaName
            },
            timeout: 3000
          });
          console.log(`[${idx}] 经纬度获取成功:`, geoRes.data);

          return {
            ...spot,
            lng: geoRes.data.lng,
            lat: geoRes.data.lat
          };
        } catch (err) {
          console.warn(`[${idx}] 未能获取 ${spot.scenicAreaName} 的经纬度:`, err);
          return spot;
        }
      })
    );

    this.scenicList = scenicListWithCoords;
    console.log("✅ 补全坐标后的 scenicList：", this.scenicList);
    console.log("step2");
  } catch (e) {
    console.error('获取景点列表失败', e);
  }
},

    // 热门景点自动滚动
    startHotScenicAutoScroll() {
      clearInterval(this.hotScenicScrollTimer);
      this.$nextTick(() => {
        const container = this.$refs.hotScenicListRef;
        if (!container) return;
        const card = container.querySelector('.hot-scenic-card');
        if (!card) return;
        const style = getComputedStyle(card);
        const cardWidth = card.offsetWidth + parseInt(style.marginRight || 0);

        this.hotScenicScrollTimer = setInterval(() => {
          if (container.scrollLeft + container.offsetWidth >= container.scrollWidth - cardWidth) {
            container.scrollLeft = 0;
          } else {
            container.scrollLeft += cardWidth;
          }
        }, 3000);
      });
    },
    // 热门攻略自动滚动
    startHotStrategyAutoScroll() {
      clearInterval(this.hotStrategyScrollTimer);
      this.$nextTick(() => {
        const container = this.$refs.hotStrategyListRef;
        if (!container) return;
        const card = container.querySelector('.hot-scenic-card');
        if (!card) return;
        const style = getComputedStyle(card);
        const cardWidth = card.offsetWidth + parseInt(style.marginRight || 0);

        this.hotStrategyScrollTimer = setInterval(() => {
          if (container.scrollLeft + container.offsetWidth >= container.scrollWidth - cardWidth) {
            container.scrollLeft = 0;
          } else {
            container.scrollLeft += cardWidth;
          }
        }, 3000);
      });
    },
    stripHtmlTags(html) {
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = html;
      return tempDiv.textContent || tempDiv.innerText || '';
    },
    async fetchHotScenicSpots() {
      try {
        const res = await axios.get('/sclike/topdetails?limit=4');
        this.hotScenicSpots = res.data;
        this.$nextTick(() => {
          this.startHotScenicAutoScroll();
        });
      } catch (error) {
        console.error('获取热门景点失败：', error);
      }
    },
    async fetchHotStrategies() {
      try {
        const res = await axios.get('/strlike/topdetails?limit=4');
        this.hotStrategies = res.data;
        this.$nextTick(() => {
          this.startHotStrategyAutoScroll();
        });
      } catch (error) {
        console.error('获取热门攻略失败：', error);
      }
    },
    goToScenicDetail(id) {
      this.$router.push(`/homepage/scenic/${id}`);
    },
    goToStrategyDetail(id) {
      this.$router.push(`/homepage/strategy/detail/${id}`);
    }
  }
};
</script>

<style scoped>
/* ...原样保留你的 style 部分... */
.hot-scenic-list-scroll {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  gap: 20px;
  padding-bottom: 10px;
  scroll-behavior: smooth;
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.hot-scenic-list-scroll::-webkit-scrollbar {
  display: none;
}

/* 卡片宽度控制，防止被压缩 */
.hot-scenic-card {
  flex: 0 0 600px;
  /* 比原来大，确保溢出 */
  min-width: 600px;
  max-width: 600px;
}

.note-author {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.author-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid #eee;
}

.author-name {
  font-size: 0.98em;
  color: #409eff;
  font-weight: bold;
}

.homepage {
  padding: 0;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}
.homepage::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background:
    linear-gradient(135deg, rgba(74, 144, 226, 0.8), rgba(107, 91, 149, 0.8)),
    url('https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&auto=format&fit=crop&w=2000&q=80') center/cover;
  z-index: 0;
  pointer-events: none;
}
.homepage > * {
  position: relative;
  z-index: 1;
}

.hero-section {
  position: relative;
  width: 100%;
  height: 700px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  margin-top: 0;
}

.hero-content h2 {
  color: rgba(252, 254, 255, 0.7);
  font-size: 4.5em;
  margin: 0 0 30px 0;
  text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.8);
  line-height: 1.1;
  text-transform: uppercase;
}

.hero-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 1;
}

.hero-video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 0;
  pointer-events: none;
}

.hero-content {
  position: relative;
  z-index: 1;
}

main {
  padding: 0px;
  max-width: 1200px;
  margin: 0 auto;
}

section {
  margin-bottom: 30px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

section h2 {
  color: #333;
  margin-top: 0;
  border-bottom: 2px solid #555;
  padding-bottom: 5px;
  margin-bottom: 15px;
  font-size: 1.5em;
}

.ranking-list p,
.notes-content p,
.group-tours-content p {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #333;
}

.scenic-content {
  display: flex;
  gap: 20px;
}

.china-map-placeholder,
.image-carousel-placeholder {
  flex: 1;
  border: 1px solid #ccc;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #eee;
  border-radius: 4px;
  overflow: hidden;
}

.view-more {
  text-align: right;
  margin-top: 10px;
}

.view-more a {
  color: #555;
  text-decoration: none;
  font-weight: bold;
  font-size: 0.9em;
}

.view-more a:hover {
  text-decoration: underline;
}

.hot-scenic-spots {
  margin-top: 30px;
}

.hot-scenic-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 10px;
  justify-content: center;
}

.hot-scenic-card {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 280px;
  max-width: 320px;
  width: 100%;
  overflow: hidden;
  position: relative;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  border: 1px solid #eee;
}

.hot-scenic-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.hot-scenic-img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  border-top-right-radius: 8px;
  border-top-left-radius: 8px;
}

.hot-scenic-info {
  padding: 15px;
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.hot-scenic-title {
  font-size: 1.2em;
  font-weight: bold;
  color: #333;
  margin-bottom: 6px;
}

.hot-scenic-desc {
  font-size: 0.97em;
  color: #777;
  line-height: 1.5;
  margin-bottom: 10px;
  min-height: 2em;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.hot-scenic-actions {
  display: flex;
  gap: 10px;
  margin-top: auto;
  align-items: center;
}

.like-button {
  background-color: #fcebeb;
  border-color: #f7a0a0;
  color: #d9534f;
  border-radius: 4px;
  padding: 4px 10px;
  font-size: 0.98em;
}

.like-button:hover {
  background-color: #f7a0a0;
  color: #fff;
  border-color: #f7a0a0;
}

.like-icon {
  margin-right: 5px;
  font-size: 1em;
}

.hot-scenic-list.hot-scenic-list-scroll {
  flex-wrap: nowrap !important;
  justify-content: flex-start !important;
}

.hot-scenic-spots:nth-of-type(3) .hot-scenic-list.hot-scenic-list-scroll .hot-scenic-card {
  flex: 0 0 calc(25% - 15px);
  min-width: 0;
  max-width: none;
  width: 100%;
}
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(40px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.hot-scenic-card {
  animation: fadeInUp 0.8s ease-out forwards;
  opacity: 0;
  transform: translateY(40px);
}

/* 让每个卡片有不同的延迟，实现阶梯式动画 */
.hot-scenic-list .hot-scenic-card:nth-child(1) { animation-delay: 0.1s; }
.hot-scenic-list .hot-scenic-card:nth-child(2) { animation-delay: 0.2s; }
.hot-scenic-list .hot-scenic-card:nth-child(3) { animation-delay: 0.3s; }
.hot-scenic-list .hot-scenic-card:nth-child(4) { animation-delay: 0.4s; }
.hot-scenic-list .hot-scenic-card:nth-child(5) { animation-delay: 0.5s; }
.hot-scenic-list .hot-scenic-card:nth-child(6) { animation-delay: 0.6s; }

/* 新增样式：让地图填满景点信息区域 */
.scenic-content-maponly {
  display: block;
}
.scenic-content-maponly .china-map-placeholder {
  width: 100%;
  height: 400px;
  background: none !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  overflow: visible;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

/* 让景点信息section无背景、无边框、无圆角 */
.scenicmain {
  background: none !important;
  box-shadow: none !important;
  border-radius: 0 !important;
  border: none !important;
  padding: 0 0 20px 0 !important;
  margin-bottom: 30px;
}
.scenicmain h2 {
  background: none;
  margin-top: 0;
  border-bottom: none;
  padding-bottom: 10px;
  color: #fff;
}
.scenic-content-maponly .china-map-placeholder {
  width: 100%;
  height: 400px;
  background: none !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  overflow: visible;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}
/* 去掉全局section对.scenicmain的影响 */
section.scenicmain {
  background: none !important;
  box-shadow: none !important;
  border-radius: 0 !important;
  border: none !important;
}

/* 让地图无任何外框、背景、边框、标题 */
.scenicmain,
.scenic-content-maponly,
.scenic-content-maponly .china-map-placeholder {
  background: none !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  padding: 0 !important;
  margin: 0 !important;
}
.scenicmain h2 { display: none !important; }

/* 热门景点轮播美化 */
.hot-scenic-spots.no-bg {
  background: none !important;
  box-shadow: none !important;
  border-radius: 0 !important;
  border: none !important;
  padding: 0 !important;
  margin-bottom: 40px;
}
.hot-title {
  color: #fff;
  font-size: 2em;
  margin-bottom: 30px;
  text-align: center;
  letter-spacing: 2px;
  font-weight: bold;
  text-shadow: 0 2px 8px rgba(0,0,0,0.18);
}
.hot-scenic-swiper-coverflow {
  width: 100%;
  max-width: 1100px;
  margin: 0 auto;
  padding-bottom: 30px;
}
.hot-scenic-swiper-coverflow .swiper-slide {
  display: flex;
  justify-content: center;
  align-items: center;
  height: auto;
  transition: transform 0.3s;
}
.hot-scenic-swiper-coverflow .swiper-slide:not(.swiper-slide-active) {
  filter: blur(1.5px) grayscale(0.2) brightness(0.95);
  opacity: 0.7;
}
.hot-scenic-card-large {
  background: #fff;
  border-radius: 32px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.18);
  overflow: hidden;
  width: 600px;
  max-width: 90vw;
  margin: 0 auto;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}
.hot-scenic-card-large:hover {
  transform: translateY(-6px) scale(1.03);
  box-shadow: 0 16px 48px rgba(0,0,0,0.22);
}
.hot-scenic-img-large {
  width: 100%;
  height: 320px;
  object-fit: cover;
  border-top-left-radius: 32px;
  border-top-right-radius: 32px;
}
.hot-scenic-info-large {
  padding: 32px 36px 24px 36px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.hot-scenic-title-large {
  font-size: 1.5em;
  font-weight: bold;
  color: #222;
  margin-bottom: 12px;
}
.hot-scenic-desc-large {
  font-size: 1.1em;
  color: #666;
  margin-bottom: 18px;
  min-height: 2em;
}
.hot-scenic-actions-large {
  margin-top: auto;
}
@media (max-width: 900px) {
  .hot-scenic-card-large {
    width: 98vw;
    border-radius: 18px;
  }
  .hot-scenic-img-large {
    height: 180px;
    border-top-left-radius: 18px;
    border-top-right-radius: 18px;
  }
  .hot-scenic-info-large {
    padding: 18px 12px 14px 12px;
  }
}

/* 热门攻略卡片美化（左右布局） */
.hot-strategy-card-row {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  min-height: 320px;
  width: 600px;
  max-width: 90vw;
  padding: 0;
  background: rgba(255,255,255,0.85);
  border-radius: 32px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.18);
  backdrop-filter: blur(4px);
  overflow: hidden;
  border: 1.5px solid rgba(255,255,255,0.28);
  transition: transform 0.25s, box-shadow 0.25s;
  cursor: pointer;
}
.hot-strategy-card-row:hover {
  transform: scale(1.035);
  box-shadow: 0 16px 48px rgba(0,0,0,0.22), 0 0 0 4px rgba(102,126,234,0.10);
}
.hot-strategy-img-side {
  width: 320px;
  min-width: 320px;
  height: 320px;
  object-fit: cover;
  border-radius: 32px 0 0 32px;
}
.hot-strategy-info-side {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 28px 28px 18px 28px;
}
.hot-strategy-title {
  font-size: 1.08em;
  font-weight: bold;
  color: #222;
  margin-bottom: 8px;
  line-height: 1.3;
}
.hot-strategy-desc {
  font-size: 0.95em;
  color: #555;
  margin-bottom: 10px;
  min-height: 2em;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.hot-strategy-bottom-side {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 18px;
}
.hot-strategy-author {
  display: flex;
  align-items: center;
  gap: 7px;
}
.hot-strategy-author-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid #eee;
}
.hot-strategy-author-name {
  font-size: 0.92em;
}
.hot-strategy-like-btn {
  font-size: 0.92em;
  padding: 2px 8px;
}
@media (max-width: 900px) {
  .hot-strategy-card-row {
    width: 98vw;
    min-height: unset;
    border-radius: 18px;
  }
  .hot-strategy-img-side {
    width: 40vw;
    min-width: 0;
    height: 180px;
    border-radius: 18px 0 0 18px;
  }
  .hot-strategy-info-side {
    padding: 14px 8px 10px 8px;
  }
}
@media (max-width: 700px) {
  .hot-strategy-card-row {
    flex-direction: column;
    width: 98vw;
    min-height: unset;
    border-radius: 10px;
  }
  .hot-strategy-img-side {
    width: 100%;
    min-width: 0;
    height: 110px;
    border-radius: 10px 10px 0 0;
  }
  .hot-strategy-info-side {
    padding: 8px 6px 6px 6px;
  }
}
</style>